import { ref, inject } from "vue";
import { useMenuStore } from '../../../store/useMenuStore'

interface Tree {
    id: string;
    label: string;
    value: string;
    children?: Tree[];
}

export const useMenuTree = () => {
    //获取API配置
    const API = inject("API") as any;
    const ApiConfig = inject("ApiConfig") as any;

    const menuStore = useMenuStore();

    const data = ref<Tree[]>([]);

    const fetchData = async () => {
        try {
            const response = await API.request(
                ApiConfig.Methods.GET,
                ApiConfig.PATH.Menu.GetMenuTree
            );

            if (response.status == "200" && response.data.code == "200") {
                const transformMenuData: any = (MenuList: any[]) => {
                    return MenuList.map((menu) => {
                        return {
                            id: menu.id,
                            label: menu.menuName,
                            value: menu.menuName,
                            children: menu.childMenuList
                                ? transformMenuData(menu.childMenuList)
                                : [],
                        };
                    });
                };
                data.value = transformMenuData(response.data.data);
            }
        } catch (error) {
            console.error(error);
        }
    };

    return {
        data,
        menuStore,
        fetchData,
    };
};